package com.draven.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.draven.common.core.BasePageQuery;
import com.draven.common.entity.Note;
import com.draven.common.entity.NoteTag;
import com.draven.common.entity.NoteTagRelation;
import com.draven.system.mapper.NoteMapper;
import com.draven.system.mapper.NoteTagRelationMapper;
import com.draven.system.service.INoteService;
import com.draven.system.service.INoteTagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 笔记Service业务层处理
 * 
 * @author draven
 */
@Service
public class NoteServiceImpl extends ServiceImpl<NoteMapper, Note> implements INoteService {

    @Autowired
    private NoteMapper noteMapper;

    @Autowired
    private NoteTagRelationMapper noteTagRelationMapper;

    @Autowired
    private INoteTagService noteTagService;

    /**
     * 分页查询笔记列表（包含分类名称）
     * 
     * @param note 笔记信息
     * @param pageQuery 分页查询参数
     * @return 笔记列表
     */
    @Override
    public IPage<Note> selectNotePageList(Note note, BasePageQuery pageQuery) {
        Page<Note> page = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
        return noteMapper.selectNotePageWithCategory(page, note.getTitle(), note.getCategoryId(), note.getStatus());
    }

    /**
     * 根据标签ID查询笔记列表
     * 
     * @param tagId 标签ID
     * @param pageQuery 分页查询参数
     * @return 笔记列表
     */
    @Override
    public IPage<Note> selectNotesByTagId(Long tagId, BasePageQuery pageQuery) {
        Page<Note> page = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
        return noteMapper.selectNotesByTagId(page, tagId);
    }

    /**
     * 查询最近笔记
     * 
     * @param limit 限制数量
     * @return 笔记列表
     */
    @Override
    public List<Note> selectRecentNotes(Integer limit) {
        return noteMapper.selectRecentNotes(limit);
    }

    /**
     * 查询热门笔记
     * 
     * @param limit 限制数量
     * @return 笔记列表
     */
    @Override
    public List<Note> selectHotNotes(Integer limit) {
        return noteMapper.selectHotNotes(limit);
    }

    /**
     * 根据笔记ID查询笔记详情
     * 
     * @param noteId 笔记ID
     * @return 笔记信息
     */
    @Override
    public Note selectNoteById(Long noteId) {
        Note note = noteMapper.selectNoteDetailById(noteId);
        if (note != null) {
            // 查询关联的标签
            List<NoteTag> tags = noteTagService.selectTagsByNoteId(noteId);
            note.setTags(tags);
            if (CollUtil.isNotEmpty(tags)) {
                note.setTagIds(tags.stream().map(NoteTag::getId).collect(Collectors.toList()));
                note.setTagNames(tags.stream().map(NoteTag::getTagName).collect(Collectors.joining(",")));
            }
        }
        return note;
    }

    /**
     * 新增笔记
     * 
     * @param note 笔记信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertNote(Note note) {
        int rows = noteMapper.insert(note);
        insertNoteTag(note);
        return rows;
    }

    /**
     * 修改笔记
     * 
     * @param note 笔记信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateNote(Note note) {
        // 删除原有的标签关联
        noteTagRelationMapper.deleteByNoteId(note.getId());
        // 重新插入标签关联
        insertNoteTag(note);
        return noteMapper.updateById(note);
    }

    /**
     * 批量删除笔记
     * 
     * @param noteIds 需要删除的笔记ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteNoteByIds(Long[] noteIds) {
        // 删除标签关联
        for (Long noteId : noteIds) {
            noteTagRelationMapper.deleteByNoteId(noteId);
        }
        return noteMapper.deleteBatchIds(Arrays.asList(noteIds));
    }

    /**
     * 删除笔记信息
     * 
     * @param noteId 笔记ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteNoteById(Long noteId) {
        // 删除标签关联
        noteTagRelationMapper.deleteByNoteId(noteId);
        return noteMapper.deleteById(noteId);
    }

    /**
     * 增加浏览量
     * 
     * @param noteId 笔记ID
     * @return 结果
     */
    @Override
    public int incrementViewCount(Long noteId) {
        return noteMapper.incrementViewCount(noteId);
    }

    /**
     * 增加点赞量
     * 
     * @param noteId 笔记ID
     * @return 结果
     */
    @Override
    public int incrementLikeCount(Long noteId) {
        return noteMapper.incrementLikeCount(noteId);
    }

    /**
     * 设置笔记置顶状态
     * 
     * @param noteId 笔记ID
     * @param isTop 是否置顶
     * @return 结果
     */
    @Override
    public int updateTopStatus(Long noteId, Integer isTop) {
        Note note = new Note();
        note.setId(noteId);
        note.setIsTop(isTop);
        return noteMapper.updateById(note);
    }

    /**
     * 设置笔记公开状态
     * 
     * @param noteId 笔记ID
     * @param isPublic 是否公开
     * @return 结果
     */
    @Override
    public int updatePublicStatus(Long noteId, Integer isPublic) {
        Note note = new Note();
        note.setId(noteId);
        note.setIsPublic(isPublic);
        return noteMapper.updateById(note);
    }

    /**
     * 新增笔记标签信息
     * 
     * @param note 笔记对象
     */
    private void insertNoteTag(Note note) {
        List<Long> tagIds = note.getTagIds();
        // 处理新创建的标签
        if (note.getTagNames() != null && !note.getTagNames().isEmpty()) {
            String[] newTagNames = note.getTagNames().split(",");
            for (String tagName : newTagNames) {
                if (!tagName.trim().isEmpty()) {
                    // 检查标签是否已存在
                    LambdaQueryWrapper<NoteTag> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(NoteTag::getTagName, tagName.trim());
                    NoteTag existingTag = noteTagService.getOne(queryWrapper);
                    
                    if (existingTag == null) {
                        // 创建新标签
                        NoteTag newTag = new NoteTag();
                        newTag.setTagName(tagName.trim());
                        noteTagService.save(newTag);
                        // 添加到标签ID列表中
                        if (tagIds == null) {
                            tagIds = new ArrayList<>();
                        }
                        tagIds.add(newTag.getId());
                    } else {
                        // 使用已存在的标签
                        if (tagIds == null) {
                            tagIds = new ArrayList<>();
                        }
                        tagIds.add(existingTag.getId());
                    }
                }
            }
        }
        
        if (CollUtil.isNotEmpty(tagIds)) {
            List<NoteTagRelation> list = tagIds.stream().map(tagId -> {
                NoteTagRelation relation = new NoteTagRelation();
                relation.setNoteId(note.getId());
                relation.setTagId(tagId);
                return relation;
            }).collect(Collectors.toList());
            
            for (NoteTagRelation relation : list) {
                noteTagRelationMapper.insert(relation);
            }
        }
    }
}